package com.alg.code;


import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


public class AESCoder extends BaseCoder {
	/**
	 * 初始化key
	 * @return
	 * @throws Exception
	 */
	public static String initKey() throws Exception{
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		//设置密钥长度
		kgen.init(128);
		//生成密钥
		SecretKey skey = kgen.generateKey();
		//返回密钥的二进制编码
		
		return encryptBASE64(skey.getEncoded());
	}
	
	/**
	 * 解密
	 * @param decryptString
	 * @param decryptKey
	 * @return
	 * @throws Exception
	 */
	
	public static byte[] decryptAES(byte[] data,String decryptKey) throws Exception{
	
		SecretKeySpec key = new SecretKeySpec(decryptBASE64(decryptKey), "AES");
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, key);
		return cipher.doFinal(data);
	}
	
	public static byte[] encryptAES(byte[] data,String encryptKey) throws Exception{
		SecretKeySpec key = new SecretKeySpec(decryptBASE64(encryptKey), "AES");
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, key);
		return cipher.doFinal(data);
	}
	
	
	public static String byteArrayToHexString(byte[] addr) {
		if (addr == null)
			return null;
		StringBuilder sb = new StringBuilder("");
		for (int i = 0; i < addr.length; i++) {
			int v = addr[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				sb.append(0);
			}
			sb.append(hv);
			if (i < addr.length - 1)
				sb.append(" ");
		}
		return sb.toString();
	}
	
	
	public static void main(String[] args) throws Exception {
		String AESKey = AESCoder.initKey();
		String text = "Hello world,ervery day d Hello world,ervery day d Hello world,ervery day d Hello world,ervery day d Hello world,ervery day d Hello world,ervery day d Hello world,ervery day d Hello world,ervery day dHello world,ervery day d";
		System.out.println("加密前的："+text.getBytes().length);
		byte[] encryptData = AESCoder.encryptAES(text.getBytes(), AESKey);
		System.out.println("length:"+encryptData.length);
		
		System.out.println("加密后的："+byteArrayToHexString(encryptData));
		byte[] decryptData = AESCoder.decryptAES(encryptData, AESKey);
		System.out.println("解密后的："+new String(decryptData));
	}
}
